package com.hmall.item.web;

import com.hmall.common.dto.ItemDTO;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> itemPageQuery(@RequestParam int page, @RequestParam int size) {
        PageDTO<Item> pageDTO = itemService.itemPageQuery(page, size);
        return pageDTO;
    }

    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ItemDTO selectItemById(@PathVariable("id") Long id) {
        ItemDTO itemDTO = itemService.selectItemById(id);
        return itemDTO;
    }

    /**
     * 新增商品
     *
     * @param item
     */
    @PostMapping("/list")
    public void insertItem(@RequestBody Item item) {
        itemService.insertItem(item);
    }

    /**
     * 商品上架、下架
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable(value = "id") Long id, @PathVariable(value = "status") Integer status) {
        String queue = status == 1?"insert.Queue":"delete.Queue";
        rabbitTemplate.convertSendAndReceive(queue,id);
        itemService.updateStatus(id, status);
    }

    /**
     * 修改商品
     *
     * @param itemDTO
     */
    @PutMapping
    public void updateItem(@RequestBody ItemDTO itemDTO) {
        itemService.updateItem(itemDTO);
    }

    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable(value = "id") Long id) {
        itemService.deleteItem(id);
    }

    @PutMapping("/stock/{itemId}/{num}")
    public void substractStock(@PathVariable(value = "itemId") Long itemId,@PathVariable(value = "num") Integer num){
        itemService.substractStock(itemId,num);
    }
    
}
